using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Diagnostics;
using Nojin.Deployment;

namespace Nojin.AutoUpdate.Launcher
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            List<string> bugs = new List<string>();

            string targetVersion = ConfigurationManager.AppSettings[Constants.TargetVersionConfigKey];
            string targetApplication = ConfigurationManager.AppSettings[Constants.StartupFileNameConfigKey];

            if (string.IsNullOrEmpty(targetVersion))
                bugs.Add("You must add a targetVersion key to appSettings in order to specify current installed version");
            if (string.IsNullOrEmpty(targetApplication))
                bugs.Add("You must add a startup key to appSettings in order to specify start-up executable assembly");

            string appFolder = Path.Combine(Environment.CurrentDirectory, targetVersion);
            string appPath = Path.Combine(appFolder, targetApplication);
            if (!File.Exists(appPath) && bugs.Count==0 )
                bugs.Add("Unable to find start-up file.");

            if (Path.GetFileName(Application.ExecutablePath).ToLower() != Constants.LauncherApplicationName)
            {
                bugs.Add("The executable filename is not valid. It must be equal to Nojin.Deployment!Nojin.Deployment.Constants.StartUpApplicationName");
            }

            if (bugs.Count > 0)
                throw new ApplicationException(string.Join(" also ", bugs.ToArray()) + ".");            

            ProcessStartInfo psi = new ProcessStartInfo(appPath,string.Join(" ",args));
            psi.WorkingDirectory = appFolder;

            Process.Start(psi);
        }
    }
}